import {
  app,
  BrowserWindow,
  desktopCapturer,
  ipcMain,
  webContents,
  globalShortcut,
  Notification,
  shell
} from "electron";
import path from "node:path";

/* 忽略Electron的警告 */
process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = "true";
app.commandLine.appendSwitch("disable-web-security");
app.commandLine.appendSwitch("disable-features", "OutOfBlinkCors"); // 允许跨域
app.commandLine.appendSwitch("--ignore-certificate-errors", "true"); // 忽略证书相关错误

let win: BrowserWindow | null = null;

async function createWindow() {
  win = new BrowserWindow({
    titleBarOverlay: { color: "#fff" },
    titleBarStyle: "default",
    minWidth: 1136,
    width: 1136,
    height: 640,
    icon: path.join(__dirname, "../public/favicon.ico"),
    frame: false,
    transparent: true,
    // hasShadow: false,
    // useContentSize: true,
    resizable: false,
    tabbingIdentifier: "true",
    webPreferences: {
      webSecurity: false,
      nodeIntegration: true,
      contextIsolation: false,
      webviewTag: true,
      preload: path.join(__dirname, "preload.js")
    }
  });

  if (process.env.VITE_DEV_SERVER_URL) {
    win.loadURL(process.env.VITE_DEV_SERVER_URL);
    globalShortcut.register("Ctrl+F5", () => {
      win.webContents.reload();
    });
  } else {
    win.loadFile(path.join(__dirname, "./dist/index.html"));
  }

  win.on("ready-to-show", () => {
    new Notification({ title: "Hello World!", body: "这是一个通知测试。" }).show();
  });

  // Test actively push message to the Electron-Renderer
  win.webContents.on("did-finish-load", () => {
    win.webContents.send("main-process-message", new Date().toLocaleString());
  });

  // Make all links open with the browser, not with the application
  win.webContents.setWindowOpenHandler(({ url }) => {
    if (url.startsWith("https:")) shell.openExternal(url);
    return { action: "deny" };
  });
}

app.whenReady().then(createWindow);

app.on("will-quit", () => {
  globalShortcut.unregisterAll();
});

app.on("browser-window-created", () => {
  console.log("window-created");
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("second-instance", () => {
  if (win) {
    // Focus on the main window if the user tried to open another
    if (win.isMinimized()) win.restore();
    win.focus();
  }
});

app.on("activate", () => {
  const allWindows = BrowserWindow.getAllWindows();
  if (allWindows.length) {
    allWindows[0].focus();
  } else {
    createWindow();
  }
});

ipcMain.on("min", () => win.minimize());
ipcMain.on("window-maximize", () => {
  if (win.isFullScreen()) {
    win.setFullScreen(false);
  } else if (win.isMaximized()) {
    win.unmaximize();
  } else {
    win.maximize();
  }
});

ipcMain.on("openDevTools", async () => {
  if (process.env.NODE_ENV === "development") {
    if (win.webContents.isDevToolsOpened()) {
      win.webContents.closeDevTools();
    } else {
      win.webContents.openDevTools({ mode: "undocked", activate: true });
    }
  }
});

ipcMain.on("close", () => win.close());
ipcMain.on("reload", () => win.reload());

const genWindow = async () =>
  await Promise.all(
    webContents
      .getAllWebContents()
      .filter((item) => {
        const win = BrowserWindow.fromWebContents(item);
        return win && win.isVisible();
      })
      .map(async (item) => {
        const win = BrowserWindow.fromWebContents(item);
        const thumbnail = await win?.capturePage();
        return {
          name: win?.getTitle() + (item.devToolsWebContents === null ? "" : "-dev"),
          id: win?.getMediaSourceId(),
          thumbnail,
          display_id: "",
          appIcon: null
        };
      })
  );

ipcMain.handle("ev:send-desktop-capturer_source", async () => {
  return [...(await desktopCapturer.getSources({ types: ["window", "screen"] })), ...(await genWindow())];
});
